package com.fooddelivery.Common.Unit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class OrderNumberGenerator {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final String PREFIX = "ORD";

    // 本地缓存序列号，减少数据库查询
    private String currentDate;
    private AtomicInteger sequence = new AtomicInteger(0);
    private int maxSequence = 0; // 当前日期已分配的最大序列号

    public synchronized String generateOrderNumber() {
        String todayStr = LocalDate.now().format(dateFormatter);

        // 如果日期变化，重置序列号
        if (!todayStr.equals(currentDate)) {
            currentDate = todayStr;
            // 查询当前日期的最大序列号
            String maxOrderNumber = jdbcTemplate.queryForObject(
                    "SELECT MAX(order_number) FROM t_order WHERE order_number LIKE ?",
                    String.class,
                    PREFIX + todayStr + "%"
            );
            if (maxOrderNumber == null) {
                // 当天没有订单，从1开始
                sequence.set(1);
                maxSequence = 1;
            } else {
                // 解析出序列号部分
                String seqStr = maxOrderNumber.substring(PREFIX.length() + 8); // 8位日期
                int seq = Integer.parseInt(seqStr);
                sequence.set(seq + 1);
                maxSequence = seq + 1;
            }
        }

        // 如果本地序列号已经用完（即已经被其他实例用到了），则重新查询数据库
        if (sequence.get() > maxSequence) {
            // 重新查询当前日期的最大序列号
            String maxOrderNumber = jdbcTemplate.queryForObject(
                    "SELECT MAX(order_number) FROM t_order WHERE order_number LIKE ?",
                    String.class,
                    PREFIX + todayStr + "%"
            );
            if (maxOrderNumber == null) {
                sequence.set(1);
                maxSequence = 1;
            } else {
                String seqStr = maxOrderNumber.substring(PREFIX.length() + 8);
                int seq = Integer.parseInt(seqStr);
                sequence.set(seq + 1);
                maxSequence = seq + 1;
            }
        }

        // 生成4位序列号（不足补零）
        String seqNum = String.format("%04d", sequence.getAndIncrement());
        return PREFIX + todayStr + seqNum;
    }

    // 提供一个重试机制，当插入订单失败时（因为订单号重复），可以重新生成订单号
    public String generateOrderNumberWithRetry(int maxRetries) {
        for (int i = 0; i < maxRetries; i++) {
            String orderNumber = generateOrderNumber();
            // 检查数据库中是否已存在（可选，因为插入时会检查，但可以提前避免）
            Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(1) FROM t_order WHERE order_number = ?",
                    Integer.class,
                    orderNumber
            );
            if (count == 0) {
                return orderNumber;
            }
        }
        throw new RuntimeException("Failed to generate unique order number after " + maxRetries + " retries");
    }
}